package fun.easycode.webterminal.common.jsch;

import cn.hutool.core.lang.SimpleCache;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JschJumpSessionPool {

    public static final JschJumpSessionPool INSTANCE = new JschJumpSessionPool();

    private final SimpleCache<String, JschJumpSession> cache = new SimpleCache<>(new HashMap<>());


    public JschJumpSession get(String id) {

        return cache.get(id, JschJumpSession::isConnected, () -> {
            JschJumpSession session = new JschJumpSession(id);
            session.connect();
            return session;
        });
    }


    public void close(String id) {
        JschJumpSession session = get(id);
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
        this.cache.remove(id);
    }

    public void closeAll() {
        JschJumpSession session;
        for (Map.Entry<String, JschJumpSession> entry : this.cache) {
            session = entry.getValue();
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
        cache.clear();
    }
}
